package cn.sxw.android.base.kt

import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import cn.sxw.android.base.utils.DeviceUtils
import com.zcs.autolayout.AutoConstraintLayout
import com.zcs.autolayout.AutoFrameLayout
import com.zcs.autolayout.AutoLinearLayout
import com.zcs.autolayout.AutoRelativeLayout
import org.greenrobot.eventbus.EventBus

/**
 * Created by ZengCS on 2021/6/25.
 * E-mail:zengcs@vip.qq.com
 * Add:中国成都
 * Desc:类说明
 */
abstract class BaseKtActivity : AppCompatActivity() {
    companion object {
        const val LAYOUT_LINEARLAYOUT = "LinearLayout"
        const val LAYOUT_FRAMELAYOUT = "FrameLayout"
        const val LAYOUT_RELATIVELAYOUT = "RelativeLayout"
        const val LAYOUT_CONSTRAINTLAYOUT = "android.support.constraint.ConstraintLayout"
        const val LAYOUT_CONSTRAINTLAYOUT_X = "androidx.constraintlayout.widget.ConstraintLayout"

        const val IS_NOT_ADD_ACTIVITY_LIST = "is_add_activity_list" //是否加入到activity的list，管理
    }

    override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
        var view: View? = null
        when (name) {
            LAYOUT_FRAMELAYOUT -> view = AutoFrameLayout(context, attrs)
            LAYOUT_LINEARLAYOUT -> view = AutoLinearLayout(context, attrs)
            LAYOUT_RELATIVELAYOUT -> view = AutoRelativeLayout(context, attrs)
            LAYOUT_CONSTRAINTLAYOUT, LAYOUT_CONSTRAINTLAYOUT_X -> view =
                AutoConstraintLayout(context, attrs)
        }
        return view ?: super.onCreateView(name, context, attrs)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (useEventBus()) //如果要使用eventbus请将此方法返回true
            EventBus.getDefault().register(this) //注册到事件主线
        // autoOrientation()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus()) //如果要使用eventbus请将此方法返回true
            EventBus.getDefault().unregister(this)
    }

    private fun autoOrientation() {
        //如果是竖排,则改为横排;反之然
        requestedOrientation = if (isTablet()) {
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        } else {
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
    }

    fun isTablet(): Boolean {
        return DeviceUtils.isTablet(this)
    }

    abstract fun useEventBus(): Boolean

    /**
     * 初始化方法，如果有RxPermission权限申请，必须在这个方法内执行
     */
    abstract fun onInit()

    // 用于懒加载的Activity提前初始化，在onInit之前执行
    open fun onReady() {}

    abstract fun initObserve()

    abstract fun initView()

    open fun initData() {}

    open fun addOnClickListener() {}
}